<template>
  <div class="modal fade" id="modal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title">部署日志</h4>
        </div>
        <div class="modal-body">
          <div id="terminal"></div>
        </div>
        <div class="modal-footer">
          <button type="button" @click="clearStorage()" class="btn btn-danger">Permanently clear log</button>
          <button type="button" @click="getTerminal().reset()" class="btn btn-info">Clear the screen</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
  </div><!-- /.modal -->
</template>

<script>

import 'xterm/css/xterm.css'
import { Terminal } from 'xterm'

export default {
  name: 'deployLogDialog',
  data: function () {
    return {
      terminal: null,
      id: 0
    }
  },
  mounted: function () {
  },
  methods: {
    setTerminal () {
      this.terminal = new Terminal({
        rendererType: 'dom',
        fontSize: 12,
        cursorStyle: 'underline', // 光标样式
        cursorBlink: true, // 光标闪烁
        disableStdin: true,
        theme: {
          foreground: '#7e9192', // 字体
          background: '#002833', // 背景色
          cursor: 'help', // 设置光标
          lineHeight: 16
        }
      })
      return true
    },
    getTerminal () {
      return this.terminal
    },
    setStorage (id, info) {
      localStorage.setItem('storage' + id, JSON.stringify(info))
    },
    clearStorage () {
      localStorage.removeItem('storage' + this.id)
      this.getTerminal().reset()
    },
    getStorage (id) {
      let str = localStorage.getItem('storage' + id)
      let info = []
      if (str) {
        info = JSON.parse(str)
      }
      return info
    },
    push (id, msg) {
      let info = this.getStorage(id)
      info.push(msg)
      this.setStorage(id, info)
      let terminal = this.getTerminal()
      if (terminal != null) {
        terminal.write(msg)
      }
    },
    recovery () {
      this.getStorage(this.id).forEach((n, i) => {
        this.getTerminal().write(n)
      })
    },
    show (id) {
      this.id = id
      $('#modal').modal('show')
      if (this.getTerminal() == null && this.setTerminal()) {
        setTimeout(() => {
          this.getTerminal().open(document.getElementById('terminal'))
          this.recovery()
        }, 200)
      } else {
        this.getTerminal().reset()
        this.recovery()
      }
    }
  }
}
</script>

<style scoped lang="less">
</style>
